package logic;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

import data.Card;

public class FileOperation {
	Card card;
	
	public ArrayList<Card> getCardList(String filename, ArrayList<Card> cards) {
		
		cards = openFile(filename, cards);
		return cards;
		
	}

	private ArrayList<Card> openFile(String filename, ArrayList<Card> cards) {
		FileReader file = null;
		String line = "";
		try {
			file = new FileReader(filename);
			@SuppressWarnings("resource")
			BufferedReader reader = new BufferedReader(file);
			while ((line = reader.readLine()) != null) {
				card = parseData(line);
				cards.add(card);
			}
		} catch (FileNotFoundException e) {
			throw new RuntimeException("File not found");
		} catch (IOException e) {
			throw new RuntimeException("IO Error occured");
		} finally {
			if (file != null) {
				try {
					file.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return cards;
	}

	
	private Card parseData(String line) {
		
		String parse = line;
		String delimiter = ".";
		String[] temp = parse.split(delimiter,4);
		String name = temp[0];
		String year = temp[1];
		String category = temp[2];
		String type = temp[3];
		Card card = new Card(name, type, category, year);
		return card;
		
	}
		

}
